<?php

namespace Kangcg\Application\Validate\Rules;

use Kangcg\Application\Validate\Validator;
use Kangcg\Helper\Validate\Base;

class Str implements RuleInterface
{
    use RuleTrait;

    public $min = null;
    public $max = null;
    protected function afterRun(&$value, string $field, array $input, Validator $validator)
    {
        if(!is_string($value)){
            return $validator->setError($this->getMessage($field));
        }

        $len = strlen($value);
        if($this->max !== null && $len > $this->max){
            return $validator->setError($this->getMessage($field, '', ":attribute 长度不能超过【:message】！"));
        }

        if($this->min !== null && $len < $this->min){
            return $validator->setError($this->getMessage($field, '', ":attribute 长度不能少于【:message】！"));
        }
    }

    public function extra($extra)
    {
        if(is_int($extra)){
            return [
                'max' => $extra,
            ];
        }

        if(isset($extra['max']) || isset($extra['min'])){
            return $extra;
        }

        if(isset($extra[0]) && isset($extra[1]) && is_int($extra[0]) && is_int($extra[1])){
            return [
                'max' => $extra[0],
                'min' => $extra[1],
            ];
        }

        return $extra;
    }
}
